//路由配置
import Vue from 'vue';
import VueRouter from 'vue-router';

/* 路由懒加载(lazy):用import的方式导入哦*/
const Home = () => import('../components/Home.vue');
const HomeNews = () => import('../components/HomeNews.vue');
const HomeMessage = () => import('../components/HomeMessage.vue');

const About = () => import('../components/About.vue');
const User = () => import('../components/User.vue');
const Profile = () => import('../components/Profile.vue');

/* 非懒加载方式
import Home from '../components/Home.vue';
import About from '../components/About.vue';
import User from '../components/User.vue'; */

//源码中执行:install方法
Vue.use(VueRouter);

const routes = [
    {
        path:'/',
        redirect:'/home'
    },
    {
        path:'/home',
        component:Home,
        //meta:元数据:描述数据的数据
        meta:{
            title:'首页'
        },
        children:[
            //子路由的path前面无需加 / 
            {
                path:'news',
                component:HomeNews
            },
            {
                path:'message',
                component:HomeMessage
            }
        ]
    },
    {
        path:'/about',
        component:About,
        meta:{
            title:'关于'
        },
        beforeEnter: (to, from, next) => {
            console.log('路由独享的守卫');
            console.log(to,from);
            next();
        }
    },
    {
        path:'/user/:uname',
        component:User,
        meta:{
            title:"用户"
        }
    },
    {
        path:'/profile',
        component:Profile,
        meta:{
            title:"档案"
        }
    }
];

const router = new VueRouter({
    mode:'history',
    routes,
    linkActiveClass:'active'
});

//全局前置路由守卫(其实就是一个钩子函数)
router.beforeEach(function (to,from,next) { 
    //从from到to
    //通过document.title设置网页的标题
    document.title = to.matched[0].meta.title;
    console.log(to,from);

    //执行下一步,不写的话会导致路由在此终断
    next();
});

//全局后置路由守卫
router.afterEach(function (to,from) {  
    //路由完毕后回调此函数
    console.log('导航完毕!');
    console.log(to,from);
})

export default router;